#include "functionsview.h"
#include "functionsmodel.h"
#include <QDebug>
#include <QIcon>
#include <QMouseEvent>
#include <QMenu>

FunctionsView::FunctionsView(QWidget * parent) : QTreeView(parent)
{
}

void FunctionsView::selectionChanged(const QItemSelection & selected, const QItemSelection &)
{
	if(!selected.indexes().isEmpty()) {
		QModelIndex idx=selected.indexes().first();
		model()->setData(idx, QVariant(), FunctionsModel::Selection);
	}
}

void FunctionsView::mousePressEvent(QMouseEvent * e)
{
    QModelIndex clickIdx(indexAt(e->pos()));

    if(e->button()==Qt::RightButton && clickIdx.isValid()) {
        QModelIndex nameIdx(clickIdx.sibling(clickIdx.row(), 0));
        bool shown=model()->data(clickIdx, FunctionsModel::Shown).toBool();
        QString actuallyShown;
        QString icon;
        if(shown) {
            icon="user-invisible";
            actuallyShown=QString(tr("Ẩn '%1'")).arg(model()->data(nameIdx).toString());
        } else {
            icon="user-online";
            actuallyShown=QString(tr("Hiện ra '%1'")).arg(model()->data(nameIdx).toString());
        }
        QMenu menu(this);
        QAction* actionShown=menu.addAction(QIcon(icon), actuallyShown);
        QAction* actionRemove=menu.addAction(QIcon("list-remove"),QString(tr("Xóa '%1'")).arg(model()->data(nameIdx).toString()));
        QAction* result=menu.exec(e->globalPos());
        if(result==actionShown) {
            model()->setData(clickIdx, !shown, FunctionsModel::Shown);
        }
        else if(result==actionRemove) {
            model()->removeRow(clickIdx.row());
            emit deleteFunc();
        }
    }
    else {
        QTreeView::mousePressEvent(e);
    }
}

